/*
 * Created by Wildish on 2016-10-28
 *
 * Contact me with keithknight@qq.com
 *
 * Copyright (c) 2016 Wildish
 *
 */

package com.wildish.qcface.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.qcloud.fr.QcloudFrSDK;
import com.wildish.customprogressdialog.CustomProgressDialog;
import com.wildish.qcface.R;
import com.wildish.qcface.util.FileUtil;
import com.wildish.qcface.util.Global;

import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 导入页面
 * 从相册或者相机中选择图片，识别并上传
 * Created by Wildish on 2016-10-26.
 */
public class ImportActivity extends Activity {
    private static int RESULT_LOAD_IMAGE = 1;
    private static int RESULT_TAKE_PHOTO = 2;

    private static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 0;
    private static final int MY_PERMISSIONS_REQUEST_CAMERA = 1;

    private ImageView ivPhoto;
    private TextView tvOutput;

    private String photoPath;
    private QcloudFrSDK qcSDK;
    private CustomProgressDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_import);
        ivPhoto = (ImageView) findViewById(R.id.iv_photo);
        tvOutput = (TextView) findViewById(R.id.tv_output);

        qcSDK = Global.getQcSDK();
        dialog = CustomProgressDialog.createDialog(this);
        dialog.setCancelable(false);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 授权成功
                    doChoosePic();
                } else {
                    // 授权失败
                    Toast.makeText(this, "您未授权应用访问外部储存，无法选择照片", Toast.LENGTH_SHORT).show();
                }
                break;
            case MY_PERMISSIONS_REQUEST_CAMERA:
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 授权成功
                    doTakePhoto();
                } else {
                    // 授权失败
                    Toast.makeText(this, "您未授权应用访问摄像头", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    public void choosePic(View view) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.READ_EXTERNAL_STORAGE)) {
            } else {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
            }
        } else {
            doChoosePic();
        }
    }

    private void doChoosePic() {
        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, RESULT_LOAD_IMAGE);
    }

    public void takePhoto(View view) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {

            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.CAMERA)) {
            } else {
                ActivityCompat.requestPermissions(this,  new String[]{Manifest.permission.CAMERA},
                        MY_PERMISSIONS_REQUEST_CAMERA);
            }
        } else {
            doTakePhoto();
        }
    }

    private void doTakePhoto() {
        Intent intent = new Intent();
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        photoPath = Global.generateTempPhotoPath();
        File file = new File(photoPath);
        file.deleteOnExit();
        file.getParentFile().mkdirs();
        Uri fileUri = Uri.fromFile(file);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        startActivityForResult(intent, RESULT_TAKE_PHOTO);
    }

    /**
     * 上传图片
     * 1. 判断图片中是否存在face，不存在则提示
     * 2. 使用图片创建用户
     * 3. 用户存在则添加face
     * @param view 上传按钮
     */
    public void uploadPhoto(View view) {
        showToast("开始上传图片");
        dialog.show();
        Global.pool.submit(new Runnable() {
            @Override
            public void run() {
                Message msg = new Message();
                try{
                    //{"codeDesc":"Success","message":"","face":[{"expression":18,"yaw":2,"roll":-1,"height":1023,"age":23,"width":1023,"face_id":"1759828077060358143","glass":true,"gender":93,"beauty":77,"pitch":11,"y":915,"x":216}],"session_id":"","errormsg":"OK","image_width":1456,"image_height":2592,"code":0,"errorcode":0}
                    JSONObject detectFaceResult = qcSDK.DetectFace(photoPath);
                    Log.e("qcface", "detectFaceResult:" + detectFaceResult.toString());
                    if(detectFaceResult.optInt("errorcode", -1) == 0) {
                        msg.what = MSG_DETECT_SUCCESS;
                        handler.sendMessage(msg);
                        uploadOrCreatePerson();
                    } else {
                        msg.what = MSG_DETECT_FAIL;
                        handler.sendMessage(msg);
                    }
                } catch(Exception e) {
                    e.printStackTrace();

                    msg.what = MSG_DETECT_FAIL;
                    handler.sendMessage(msg);
                }
            }
        });
    }

    private void uploadOrCreatePerson() {
        List<String> list = new ArrayList<>();
        list.add(Global.GROUP_NAME);
        try{
            JSONObject result = qcSDK.NewPerson(photoPath, Global.cardId, list, Global.name);
            Log.e("qcface", "new person:" + result.toString());
            if(result.optInt("errorcode") == 0) {
                handler.sendEmptyMessage(MSG_NEWPERSON_SUCCESS);
            } else if(result.optInt("errorcode") == Global.ERROR_PERSON_EXISTED) {
                handler.sendEmptyMessage(MSG_PERSON_EXIST);

                List<String> faceList = new ArrayList<>();
                faceList.add(photoPath);
                JSONObject addResult = qcSDK.AddFace(Global.cardId, faceList);
                Log.e("qcface", "add face:" + addResult.toString());
                if(addResult.optInt("errorcode") == 0) {
                    handler.sendEmptyMessage(MSG_ADDFACE_SUCCESS);
                } else {
                    handler.sendEmptyMessage(MSG_ADDFACE_FAIL);
                }
            } else {
                handler.sendEmptyMessage(MSG_COMMON_ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
            handler.sendEmptyMessage(MSG_COMMON_ERROR);
        }
    }

    private static final int MSG_COMMON_ERROR = 0;
    private static final int MSG_DETECT_SUCCESS = 1;
    private static final int MSG_DETECT_FAIL = 2;
    private static final int MSG_NEWPERSON_SUCCESS = 3;
    private static final int MSG_PERSON_EXIST = 4;
    private static final int MSG_ADDFACE_SUCCESS = 5;
    private static final int MSG_ADDFACE_FAIL = 6;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_COMMON_ERROR:
                    showToast("操作失败，请重试");
                    dialog.hide();
                    break;
                case MSG_DETECT_FAIL:
                    showToast("未检测到人脸，请换张图片重试");
                    clearImageView();
                    dialog.hide();
                    break;
                case MSG_DETECT_SUCCESS:
                    showToast("上传图片");
                    break;
                case MSG_NEWPERSON_SUCCESS:
                    showToast("成功创建用户图片");
                    dialog.hide();
                    break;
                case MSG_PERSON_EXIST:
                    showToast("用户已经存在，为当前用户添加face");
                    break;
                case MSG_ADDFACE_SUCCESS:
                    showToast("为用户增加人脸成功");
                    dialog.hide();
                    break;
                case MSG_ADDFACE_FAIL:
                    showToast("为用户增加人脸失败");
                    dialog.hide();
                    break;
            }
        }
    };

    private void clearImageView() {
        ivPhoto.setImageResource(0);
        ivPhoto.setImageDrawable(null);
        ivPhoto.setImageResource(android.R.color.transparent);
    }

    private void showToast(String msg) {
        String nowTimeStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        tvOutput.append(nowTimeStr + " -- " + msg + "\n");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // 选择图片
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            photoPath = cursor.getString(columnIndex);
            cursor.close();
            ivPhoto.setImageBitmap(BitmapFactory.decodeFile(photoPath));
        }
        // 拍摄照片
        if(requestCode == RESULT_TAKE_PHOTO && resultCode == RESULT_OK) {
            File file = new File(photoPath);
            if(file.exists()) {
                File destFile = new File(Global.generateTempPhotoPath());
                FileUtil.compressImage(file, destFile, 70);

                photoPath = destFile.getAbsolutePath();
                ivPhoto.setImageBitmap(BitmapFactory.decodeFile(photoPath));
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(dialog != null) {
            dialog.dismiss();
        }
    }

    /**
     10-27 17:06:16.103 19841-19847/? E/jdwp: Failed sending reply to debugger: Broken pipe
     10-27 17:07:02.363 19841-20993/? E/qcface: detectFaceResult:{"codeDesc":"Success","message":"","face":[{"expression":6,"yaw":3,"roll":2,"height":851,"age":28,"width":851,"face_id":"1760789323496620031","glass":true,"gender":93,"beauty":69,"pitch":1,"y":989,"x":285}],"session_id":"","errormsg":"OK","image_width":1456,"image_height":2592,"code":0,"errorcode":0}
     10-27 17:07:28.343 19841-20993/? E/qcface: new person:{"codeDesc":"InvalidParameter","message":"-1302-ERROR_PERSON_EXISTED","session_id":"","person_id":"411303198705082114","group_ids":[],"errormsg":"ERROR_PERSON_EXISTED","suc_group":0,"code":4000,"errorcode":-1302,"suc_face":0}
     10-27 17:07:39.373 19841-20993/? E/qcface: add face:{"codeDesc":"Success","message":"","session_id":"","face_ids":["1760789939809746943"],"added":1,"errormsg":"OK","ret_codes":[0],"code":0,"errorcode":0}
     */
}
